﻿
//
//
//

namespace Microsoft.OpenTurf.Silverlight.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;
    using Microsoft.OpenTurf.Silverlight.Common;
    using Microsoft.OpenTurf.Silverlight.Shared;

    public class MenuViewModel : MenuControlBase
    {
        private string _baseUrl;
        #region ctor
        public MenuViewModel()
        {
            base.Initialize();
            Initialize();
            _baseUrl = ((App)App.Current).BaseUrl;
            // Hack: Twitter will be abstracted into new IMenuComponent Feature
            InitializeTwitter();
        }
        #endregion

        #region Command Methods
        public override void HandleClick(RoutedEventArgs e)
        {
            CheckBox box = e.OriginalSource as CheckBox;
            IFeed feed = box.DataContext as IFeed;

            Messenger.Default.Send<IFeed>(feed, (box.IsChecked ?? false) ? NotificationTokens.CreateOrShowLayer : NotificationTokens.HideLayer);
        }
        #endregion

        #region Methods
        /// <summary>
        /// 
        /// </summary>
        public void Initialize()
        {
            Messenger.Default.Register<Dictionary<string, string>>(this, NotificationTokens.LoadDataSources, e =>
            {
                foreach (var item in e.Values)
                {
                    Uri url = new Uri(item);

                    IFeedSource feedSource = new GenericFeedSource();
                    FeedProvider provider = new FeedProvider(_baseUrl, feedSource);

                    provider.ProcessFeedSource += new FeedSourceDownloadCompleteEventHandler(LoadFeedSource);
                    provider.DownloadAtomFeedAsync(url);
                }
            });
        }
        private void LoadFeedSource(FeedSourceEventArgs e)
        {
            MenuItems.Add(e.FeedSource);
            RaisePropertyChanged("MenuItems");
        }
        #endregion

        // Hack: Twitter will be abstracted into new IMenuComponent Feature
        #region Twitter
        IFeed twitterFeed;
        public string TwitterButtonText { get; set; }
        public RelayCommand<RoutedEventArgs> TwitterClicked { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public void InitializeTwitter()
        {
            twitterFeed = new GenericFeed(); //IoC.Container.Resolve(typeof(IFeed), "feed") as IFeed;
            twitterFeed.ID = Guid.NewGuid().ToString();
            twitterFeed.Title = "Twitter";
            twitterFeed.Summary = string.Format("Displays a pinpoint for each geo-located tweet in a {0} of the center of the map.", AppGlobals.SEARCH_RADIUS);
            twitterFeed.Icon = new Uri("/Content/images/twitter.png", UriKind.Relative);

            TwitterButtonText = "Local Tweets";
            TwitterClicked = new RelayCommand<RoutedEventArgs>(e =>
            {
                CheckBox button = e.OriginalSource as CheckBox;

                if (button.IsChecked ?? false)
                {
                    RequestMapUpdateForTwitter();
                }
                else
                {
                    Messenger.Default.Send<IFeed>(twitterFeed, NotificationTokens.HideLayer);
                }
            });
            Messenger.Default.Register<MapMessage<MapPoint>>(this, MapMessages.MapCenterResponse, (mapMessage) =>
            {
                UpdateTwitter(twitterFeed, mapMessage.Location);
            });
        }
        /// <summary>
        /// 
        /// </summary>
        private void RequestMapUpdateForTwitter()
        {
            Messenger.Default.Send<MapMessage<MapPoint>>(new MapMessage<MapPoint>(new MapPoint()), MapMessages.MapCenterRequest);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="point"></param>
        private void UpdateTwitter(IFeed feed, MapPoint point)
        {
            string twitterUrl = string.Format(AppGlobals.TWITTER_TEMPLATE, point.Latitude, point.Longitude, AppGlobals.SEARCH_RADIUS);
            Uri twitterUri = new Uri(twitterUrl);
            
            feed.Link = twitterUri;

            FeedProvider<TwitterFeedItem> provider = new FeedProvider<TwitterFeedItem>(feed);
            provider.ProcessFeed += new FeedDownloadCompleteEventHandler(ProcessFeed);
            provider.DownloadJsonFeedAsync(twitterUri);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        public void ProcessFeed(FeedEventArgs e)
        {
            if (e != null)
                Messenger.Default.Send<IFeed>(e.Feed, NotificationTokens.CreateOrShowLayer);
        }
        #endregion
    }
}